package com.demospringboot.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Date;

public class JwtUtil {
    // 建议放到配置文件
    private static final String SECRET = "demospringboot-secret-key";
    // token 有效期（单位：毫秒），例如 24 小时
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    // 生成 token
    public static String createToken(String username, String role) {
        Date now = new Date();
        Date expire = new Date(now.getTime() + EXPIRE_TIME);
        return JWT.create()
                .withSubject(username)
                .withClaim("role", role)
                .withIssuedAt(now)
                .withExpiresAt(expire)
                .sign(Algorithm.HMAC256(SECRET));
    }

    // 校验 token 并返回解码对象
    public static DecodedJWT verify(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        return verifier.verify(token);
    }

    // 从 token 获取用户名
    public static String getUsername(String token) {
        return verify(token).getSubject();
    }

    // 从 token 获取角色
    public static String getRole(String token) {
        return verify(token).getClaim("role").asString();
    }
} 